package top.kaoshanji.p1ch02e;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandleProxies;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/1/4 18:32
 */
public class MethodHandleProxiesExample01 {

    private static final Logger logger = LogManager.getLogger(MethodHandleProxiesExample01.class);

    public static void main(String[] args) throws Throwable {

        new MethodHandleProxiesExample01().asInterfaceInstance();

    }

    public void asInterfaceInstance() throws Throwable {
        logger.info("...代码清单 p1ch02e-01：MethodHandleProxies#asInterfaceInstance的使用示例...");

        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle mh = lookup.findVirtual(MethodHandleProxiesExample01.class, "doSomething", MethodType.methodType(void.class));
        mh = mh.bindTo(this);
        Runnable runnable = MethodHandleProxies.asInterfaceInstance(Runnable.class, mh);
        new Thread(runnable).start();

    }

    public void doSomething() {
        System.out.println("WORK");
    }

}
